package com.atguigu.atcrowdfunding.manager.controller;

import com.atguigu.atcrowdfunding.bean.Permission;
import com.atguigu.atcrowdfunding.bean.Role;
import com.atguigu.atcrowdfunding.controller.BaseController;
import com.atguigu.atcrowdfunding.manager.service.PermissionService;
import com.atguigu.atcrowdfunding.manager.service.RoleService;
import com.atguigu.atcrowdfunding.util.AjaxResult;
import com.atguigu.atcrowdfunding.util.Page;
import com.atguigu.atcrowdfunding.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xzt
 * @create 2021-02-26 16:17
 */
@Controller
@RequestMapping("/role")
public class RoleController extends BaseController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @RequestMapping("/index")
    public String index() {
        return "role/index";
    }

    @ResponseBody
    @RequestMapping("/doIndex")
    public Object index(@RequestParam(value = "pageNo", defaultValue = "1", required = false) Integer pageNo,
                        @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                        String queryText) {
        AjaxResult ajaxResult = new AjaxResult();
        try {

            Map<String, Object> paramMap = new HashMap();

            paramMap.put("pageNo", pageNo);
            paramMap.put("pageSize", pageSize);

            if (StringUtil.isNotEmpty(queryText)) {

                if (queryText.contains("%")) {
                    queryText = queryText.replaceAll("%", "\\\\%");
                }

                paramMap.put("queryText", queryText);
            }

            Page page = roleService.queryPage(paramMap);

            ajaxResult.setSuccess(true);
            ajaxResult.setPage(page);
            ajaxResult.setMessage("查询数据成功");
        } catch (Exception e) {
            ajaxResult.setSuccess(false);
            ajaxResult.setMessage("查询数据失败");
            e.printStackTrace();
        }


        return ajaxResult;
    }

    @RequestMapping("toAssignPermission")
    public String toAssignPermission() {
        return "role/assignPermission";
    }

    @ResponseBody
    @RequestMapping("/loadDataAsync")
    public Object loadDataAsync(Integer roleId) {
        start();
        List<Permission> root = new ArrayList<>();

        List<Permission> childredPermissions = permissionService.queryAllPermission();

        //根据角色id，查询该角色之前所分配过的许可
        List<Integer> permissionsForRoleId = permissionService.queryPermissionByRoleid(roleId);

        HashMap<Integer, Permission> map = new HashMap<>();

        for (Permission innerpermission : childredPermissions) {
            map.put(innerpermission.getId(), innerpermission);
            if(permissionsForRoleId.contains(innerpermission.getId())){
                innerpermission.setChecked(true);
            }
        }

        for (Permission permission : childredPermissions) {
            Permission child = permission;

            if (child.getPid() == null) {
                root.add(child);
            } else {
                Permission parent = map.get(child.getPid());
                parent.getChildren().add(child);
            }
        }
        return root;
    }

    @ResponseBody
    @RequestMapping("/doAssignPermission")
    public Object doAssignPermission(@RequestParam("roleId") Integer roleId,@RequestParam("ids[]") Integer[] ids){

        AjaxResult ajaxResult = new AjaxResult();
        try {
            int count = roleService.saveRolePermissionRelationship(roleId,ids);
            ajaxResult.setSuccess(count == ids.length);
            ajaxResult.setMessage("保存成功");
        }catch (Exception e){
            ajaxResult.setSuccess(false);
            ajaxResult.setMessage("保存失败");
            e.printStackTrace();
        }
        return ajaxResult;
    }

    @RequestMapping("/toAdd")
    public String toAdd(){
        return "role/add";
    }

    @ResponseBody
    @RequestMapping("/doAdd")
    public Object doAdd(Role role){

        AjaxResult ajaxResult = new AjaxResult();
        System.out.println(role);
        try {

            int count = roleService.addRole(role);

            if(count == 1){
                ajaxResult.setMessage("数据保存成功");
                ajaxResult.setSuccess(true);
            }else{
                ajaxResult.setMessage("数据保存失败");
                ajaxResult.setSuccess(false);
            }

        }catch (Exception e){
            ajaxResult.setMessage("数据保存失败");
            ajaxResult.setSuccess(false);
            e.printStackTrace();
        }

        return ajaxResult;
    }

    @RequestMapping("/toUpdate")
    public String toUpdate(@RequestParam("id") Integer id, Model model){

        Role role = roleService.queryRoleById(id);

        model.addAttribute("role",role);
        return "role/update";
    }

}
